/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.prod;

import dp1.titandevelop.titano.bean.Estado;
import dp1.titandevelop.titano.persistent.Producto;
import dp1.titandevelop.titano.persistent.ProductoProveedor;
import dp1.titandevelop.titano.persistent.Proveedor;
import dp1.titandevelop.titano.service.ProductoProveedorService;
import dp1.titandevelop.titano.service.ProductoService;
import dp1.titandevelop.titano.service.ProveedorService;
import java.awt.Dimension;
import java.awt.Frame;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author dorita
 */
public class DetalleProveedores extends javax.swing.JInternalFrame {
    ProductoService sp = new ProductoService();
    ProveedorService spe= new ProveedorService();
    ProductoProveedorService spp= new ProductoProveedorService();
    Producto producto;
    
    private ArrayList<ProductoProveedor> listaProveedores;
    private ArrayList<ProductoProveedor> listaProveedorEliminados;
    /**
     * Creates new form DetalleProveedores
     */
    public DetalleProveedores(Producto p) {
        initComponents();
        producto =p;
        this.listaProveedorEliminados = new ArrayList<ProductoProveedor>();
        this.listaProveedores=this.sp.buscaProveedores(p);
        this.tblProveedores.setModel(this.modeloProveedor);
        
    }
    
     public void RefrescarTablaProovedor() {
        
        AbstractTableModel aux = (AbstractTableModel) this.tblProveedores.getModel();
           // this.inhabilitaBotones();
        aux.fireTableDataChanged();
        }
     
      //Llena nuevos insumos a la lista de Proveedores
    public void Llenar_Proovedores(Proveedor p,  float precio) {
        
        //Crea el objeto receta para pasarlo a la lista a apartir del insumo ingresado
        short calificacion=0;
        ProductoProveedor ap =new ProductoProveedor();
        ap.setToProveedor(p);
        ap.setCalificacioncalidad(calificacion);
        ap.setPrecio(precio);
        Estado e=new Estado();
        ap.setEstado(e.getActivo());
        listaProveedores.add(ap);
        
       }

    private AbstractTableModel modeloProveedor = new AbstractTableModel() {
        public int getRowCount() {
            if (listaProveedores!=null)
            return listaProveedores.size();
            else return 0;
        }

        public int getColumnCount() {
        return 2;
        }

        String [] titles = {"Proveedor","Precio"};

        @Override
        public boolean isCellEditable(int row, int column) {
           
                if( column == 1 ) return true; 
                //if( column == 2 ) return true; 
                else return false;
        }
     
        public void setValueAt(Object value, int row, int col) {
            
            if ( col == 1 ) {           
                ProductoProveedor r=listaProveedores.get(row);
                r.setPrecio(Float.parseFloat(""+value));
                listaProveedores.set(row, r);
            }
            this.fireTableDataChanged();
        };
        public String getColumnName(int col){
        return titles[col];
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
        //String res=null;
        ProductoProveedor ap=listaProveedores.get(rowIndex);
            switch (columnIndex){
            case 0: return ap.getToProveedor().getRazonsocial();
            case 1: return ap.getPrecio();
            }
            return null;
            } 
    };
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlProveedores = new javax.swing.JPanel();
        jPanel7 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblProveedores = new javax.swing.JTable();
        btnEliminaProv = new javax.swing.JButton();
        btnDetalleProv = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setResizable(true);

        pnlProveedores.setBorder(javax.swing.BorderFactory.createTitledBorder("Proveedores"));

        jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder("Lista de Proveedores"));

        tblProveedores.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane3.setViewportView(tblProveedores);

        btnEliminaProv.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/eliminar.png"))); // NOI18N
        btnEliminaProv.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminaProvActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnEliminaProv))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 486, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEliminaProv)
                .addContainerGap())
        );

        btnDetalleProv.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/agregar.png"))); // NOI18N
        btnDetalleProv.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDetalleProvActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlProveedoresLayout = new javax.swing.GroupLayout(pnlProveedores);
        pnlProveedores.setLayout(pnlProveedoresLayout);
        pnlProveedoresLayout.setHorizontalGroup(
            pnlProveedoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlProveedoresLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlProveedoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlProveedoresLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnDetalleProv)))
                .addContainerGap())
        );
        pnlProveedoresLayout.setVerticalGroup(
            pnlProveedoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlProveedoresLayout.createSequentialGroup()
                .addComponent(btnDetalleProv)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/grabar.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(421, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(1, 1, 1)
                .addComponent(jButton2)
                .addGap(8, 8, 8))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(pnlProveedores, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(298, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addGap(8, 8, 8))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(1, 1, 1)
                    .addComponent(pnlProveedores, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(71, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnEliminaProvActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminaProvActionPerformed
        listaProveedores.remove(this.tblProveedores.getSelectedRow());
        this.RefrescarTablaProovedor();      // TODO add yo        // TODO add your handling code here:
    }//GEN-LAST:event_btnEliminaProvActionPerformed

    private void btnDetalleProvActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDetalleProvActionPerformed
        Frame f = JOptionPane.getFrameForComponent(this);
        ModulosT_PRO_BuscarProveedores dialog = new ModulosT_PRO_BuscarProveedores(f,true, this.listaProveedores);
        //this.getParent().add(dialog);
        dialog.setVisible(true);
    }//GEN-LAST:event_btnDetalleProvActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        ArrayList<ProductoProveedor> listaAgregarP = new ArrayList<ProductoProveedor>();
            ArrayList<ProductoProveedor> listaActualizarP = new ArrayList<ProductoProveedor>();
        this.sp.EliminaProveedores(this.listaProveedorEliminados);
        //Luego seleccionamos los elementos de la lista que seran editados y los que seran agregados
        for (int i=0; i<this.listaProveedores.size();i++)
        {
            ProductoProveedor r = this.spp.buscarPorProdProv(producto,listaProveedores.get(i).getToProveedor());
            if (r!=null)
            {
                //Editamos los elementos existentes
                listaActualizarP.add(this.listaProveedores.get(i));
            }
            else listaAgregarP.add(this.listaProveedores.get(i));
        }
        //Editamos
        this.sp.ActualizaProveedores(listaActualizarP);
         
        //Luego agregamos los insumos nuevos
        this.sp.InsertaProveedores(producto.getIdproducto(), listaAgregarP);
        
        //Volvemos a la ventana anterior.
         ModulosT_PRO.AdmProductos = new ModulosT_PRO_Productos();
        this.getParent().add( ModulosT_PRO.AdmProductos);

        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize =  ModulosT_PRO.AdmProductos.getSize();
         ModulosT_PRO.AdmProductos.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                (desktopSize.height - jInternalFrameSize.height) / 4);

         ModulosT_PRO.AdmProductos.show();
        ModulosT_PRO.detalleProveedor=null;
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
         ModulosT_PRO.AdmProductos = new ModulosT_PRO_Productos();
        this.getParent().add( ModulosT_PRO.AdmProductos);

        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize =  ModulosT_PRO.AdmProductos.getSize();
         ModulosT_PRO.AdmProductos.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                (desktopSize.height - jInternalFrameSize.height) / 4);

         ModulosT_PRO.AdmProductos.show();
        ModulosT_PRO.detalleProveedor=null;
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDetalleProv;
    private javax.swing.JButton btnEliminaProv;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JPanel pnlProveedores;
    private javax.swing.JTable tblProveedores;
    // End of variables declaration//GEN-END:variables
}
